/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheart.server;

import gameheart.transport.MyException;
import gameheart.transport.NetworkTransporter;
import gameheart.transport.Transporter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *lop khoi tao game server, them cac listener
 * @author win7
 */
public class GameServerCanvas implements Runnable {

    private Transporter _localTransporter = null;
    private ServerSocket _serverSocket = null;

    public GameServerCanvas() {
    }

    public void InitServer(Transporter localTransporter, int port) throws IOException {
        _localTransporter = localTransporter;
        _serverSocket = new ServerSocket(port);
    }

    public void run() {
        try {
            int soClient = 4;
            GameManager manager = new GameManager();
            manager.playerNumber = soClient;
            Thread th;
            ServerAdapterManager adapterManager = new ServerAdapterManager(soClient);
            //adapterManager.adapters = new AtomicReferenceArray<ServerAdapter>(4);
            ServerController controller = new ServerController(manager, adapterManager);
//            adapterManager.adapters.set(0, new ServerAdapter(_localTransporter, controller));
//            adapterManager.adapters.get(0).setUserID(0);
//            adapterManager.adapters.get(0).SendUserIdOfPlayer(0);
//            th = new Thread(adapterManager.adapters.get(0));
//            th.start();
            adapterManager.CreateServerAdapter(_localTransporter, controller);
            for (int index = 1; index < soClient; index++) {

                Socket socket = _serverSocket.accept();
                Transporter transporter = new NetworkTransporter(socket);
//                adapterManager.adapters.set(index, new ServerAdapter(transporter, controller));
//                adapterManager.adapters.get(index).setUserID(index);
//                adapterManager.adapters.get(index).SendUserIdOfPlayer(index);
//                th = new Thread(adapterManager.adapters.get(index));
//                th.start();
                adapterManager.CreateServerAdapter(transporter, controller);

            }
           // CardServer[][] cards = manager.ChiaBai();
//            for (int index = 0; index < soClient; ++index)
//            {
//                adapterManager.adapters.get(index).sendDealRequest(cards[index]);
//                adapterManager.adapters.get(index).SendPassCardRequest(GameManager.PassCardDirection.Left);
//
//            }
        } catch (IOException ex) {
            Logger.getLogger(GameServerCanvas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MyException myEx) {
            Logger.getLogger(GameServerCanvas.class.getName()).log(Level.SEVERE, null, myEx);
        }
    }
}
